/**
 * 初始化收款登记详情对话框
 */
var CollectBasicInformationInfoDlg = {
    collectBasicInformationInfoData : {}
};

/**
 * 清除数据
 */
CollectBasicInformationInfoDlg.clearData = function() {
    this.collectBasicInformationInfoData = {};
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
CollectBasicInformationInfoDlg.set = function(key, val) {
    this.collectBasicInformationInfoData[key] = (typeof val == "undefined") ? $("#" + key).val() : val;
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
CollectBasicInformationInfoDlg.get = function(key) {
    return $("#" + key).val();
}

/**
 * 关闭此对话框
 */
CollectBasicInformationInfoDlg.close = function() {
    parent.layer.close(window.parent.CollectBasicInformation.layerIndex);
}

/**
 * 收集数据
 */
CollectBasicInformationInfoDlg.collectData = function() {
    this
    .set('id')
    .set('collectId')
    .set('collectDate')
    .set('collectTradePerson')
    .set('collectCheck')
    .set('collectCarId')
    .set('collectCarDriver')
    .set('collectCarDriverTell')
    .set('collectCarDriverMobile')
    .set('collectCarNumber')
    .set('collectRouteId')
    .set('collectRouteStart')
    .set('collectRouteEnd')
    .set('collectSumGoodsFreight')
    .set('collectSumGoodsMessagefee')
    .set('collectSumGoodsPickupCharge')
    .set('collectRouteTransferStation')
    .set('collectSumFee')
    .set('collectThisMoney')
    .set('collectUncollectMoney')
    .set('collectType')
    .set('collectRemark');
}

function test(){
	
	var isFine = true;
	
	if($("#collectThisMoney").val()==""){
		alert("本次收款不能为空！");
		$("#collectThisMoney").focus();
		isFine = false;
		return isFine;
	}
	
	if($("#collectDate").val()==""){
		alert("收款日期不能为空！");
		$("#collectDate").focus();
		isFine = false;
		return isFine;
	}
	return true;
}
	
/**
 * json数据的工具转换
 * 
 */
//form序列化，转成单个json对象
$.fn.serializeObject = function()    
{    
   var o = {};    
   var a = this.serializeArray();    
   $.each(a, function() {    
       if (o[this.name]) {    
           if (!o[this.name].push) {    
               o[this.name] = [o[this.name]];    
           }    
           o[this.name].push(this.value || '');    
       } else {    
           o[this.name] = this.value || '';    
       }    
   });    
   return o;    
};  

//form序列化，转成json的list
$.fn.serializeJson = function(){
    var jsonData1 = {};
    var serializeArray = this.serializeArray();
    // 先转换成{"id": ["12","14"], "name": ["aaa","bbb"], "pwd":["pwd1","pwd2"]}这种形式
    $(serializeArray).each(function () {
        if (jsonData1[this.name]) {
            if ($.isArray(jsonData1[this.name])) {
                jsonData1[this.name].push(this.value);
            } else {
                jsonData1[this.name] = [jsonData1[this.name], this.value];
            }
        } else {
            jsonData1[this.name] = this.value;
        }
    });
    // 再转成[{"id": "12", "name": "aaa", "pwd":"pwd1"},{"id": "14", "name": "bb", "pwd":"pwd2"}]的形式
    var vCount = 0;
    // 计算json内部的数组最大长度
    for(var item in jsonData1){
        var tmp = $.isArray(jsonData1[item]) ? jsonData1[item].length : 1;
        vCount = (tmp > vCount) ? tmp : vCount;
    }

    if(vCount > 1) {
        var jsonData2 = new Array();
        for(var i = 0; i < vCount; i++){
            var jsonObj = {};
            for(var item in jsonData1) {
                jsonObj[item] = jsonData1[item][i];
            }
            jsonData2.push(jsonObj);
        }
        return JSON.stringify(jsonData2);
    }else{
        return "[" + JSON.stringify(jsonData1) + "]";
    }
};


/**
 * 提交添加
 */
CollectBasicInformationInfoDlg.addSubmit = function() {

	if(test()==true){
		var modelCollection = {};
	    var jsonArray = JSON.parse($("#collectCarryInformation").serializeJson());
	    modelCollection.collectCarryInformations = jsonArray;
	    modelCollection.collectBasicInformation = $("#collectBasicInformation").serializeObject();
	    var jsonData = JSON.stringify(modelCollection);
	    $.ajax({
			async : false,
			type : 'post',
			url : Feng.ctxPath+'/collectBasicInformation/add',
			contentType : "application/json;charset=UTF-8",
			data :jsonData,
			success : function(data) {
				if (data == 'SUCCESS') {
					Feng.success("添加成功!");
			        window.parent.CollectBasicInformation.table.refresh();
			        CollectBasicInformationInfoDlg.close();
				} else {
					 Feng.error("添加失败!");
				}
			},
			error : function(data) {
				 Feng.error("添加失败!");
			}
		});
	}
}

/**
 * 提交修改
 */
CollectBasicInformationInfoDlg.editSubmit = function() {

	if(test()==true){
		var modelCollection = {};
	    var jsonArray = JSON.parse($("#collectCarryInformation").serializeJson());
	    modelCollection.collectCarryInformations = jsonArray;
	    modelCollection.collectBasicInformation = $("#collectBasicInformation").serializeObject();
	    var jsonData = JSON.stringify(modelCollection);
	    console.log("修改");
	    console.log(jsonData);
	    $.ajax({
			async : false,
			type : 'post',
			url : Feng.ctxPath+'/collectBasicInformation/update',
			contentType : "application/json;charset=UTF-8",
			data :jsonData,
			success : function(data) {
				if (data == 'SUCCESS') {
					Feng.success("编辑成功!");
			        window.parent.CollectBasicInformation.table.refresh();
			        CollectBasicInformationInfoDlg.close();
				} else {
					 Feng.error("编辑失败!");
				}
			},
			error : function(data) {
				 Feng.error("编辑失败!");
			}
		});
	}
}
var timer="";

//获取合同信息的下拉框
$("#searchContract").bind("keyup click",function(){
	clearData();
	//获取合同号
	var contractNumber = $("#searchContract").val();
	//显示下拉框
	var pName = $("#searchContract");
	var pNameOffset = $("#searchContract").offset();
	
  clearTimeout(timer);
	//清空查询信息
	$("#show-Contract").empty();
	
	
	timer = setTimeout(function(){
    $.ajax({
           url: Feng.ctxPath + '/collectBasicInformation/querybycontractnumber', 
           type: "POST",
              data :{"searchContract":contractNumber} ,
           dataType:"json",
           success:function(data){
	          	   var receiveBasicInformations = data;
	          	   if(JSON.stringify(receiveBasicInformations) === '[]'){
	          		 $("#showContract").css({
	            	        left : pNameOffset.left + "px",
	            	        top : pNameOffset.top + pName.outerHeight() + "px"
	            	    }).hide();
	          	   }else{
	          		  
	          		 for(i in receiveBasicInformations){
	          			 var index = parseInt(i)+1;
	                     var $li = $("<li class='XX'></li>");
	                     var receiveBasicInformation = receiveBasicInformations[i];
	                     $li.text(index+"."+receiveBasicInformation.receive_contract_number+"("+receiveBasicInformation.receiveConsigner+"-->"+receiveBasicInformation.receiveConsignee+")");
	                     $("#show-Contract").append($li);
	                 }       
	            	 $("#showContract").css({
	            	        left : pNameOffset.left + "px",
	            	        top : pNameOffset.top + pName.outerHeight() + "px"
	            	    }).show();
	
	                 $("#show-Contract li.XX").each(function(){
	                       $(this).click(function(){
	                    	   var text = $(this).text().split(".")[1];
	                    	   text = text.substring(0,text.indexOf("("));
	                            $("#showContract").css({
	    	            	        left : pNameOffset.left + "px",
	    	            	        top : pNameOffset.top + pName.outerHeight() + "px"
	    	            	    }).hide();
	                            
	                          //清空查询信息
	                        	$("#show-Carry").empty();
	                            
	                            $.ajax({
	                            	 url: Feng.ctxPath + '/collectBasicInformation/getcarrynumber', 
		                             type: "POST",
		                             data :{"contractNumber":text} ,
		                             dataType:"json",
		                             success:function(data){
		                            	var carrys = data;
		                            	if(JSON.stringify(carrys) === '[]'){
		               	          		 $("#showCarry").css({
		               	            	        left : pNameOffset.left + "px",
		               	            	        top : pNameOffset.top + pName.outerHeight() + "px"
		               	            	    }).hide();
		               	          	   }else{
		               	          		  
		               	          		 for(i in carrys){
		               	          			 var index = parseInt(i)+1;
		               	                     var $li = $("<li class='XX'></li>");
		               	                     var carry = carrys[i];
		               	                     $li.text(index+"."+carry.foreignKeyCarryId);
		               	                     $("#show-Carry").append($li);
		               	                 }       
		               	            	 $("#showCarry").css({
		               	            	        left : pNameOffset.left + "px",
		               	            	        top : pNameOffset.top + pName.outerHeight() + "px"
		               	            	    }).show();
		               	            	$("#show-Carry li.XX").each(function(){
		         	                       $(this).click(function(){
		         	                    	   var text1 = $(this).text().split(".")[1];
		         	                            $("#showCarry").css({
		         	    	            	        left : pNameOffset.left + "px",
		         	    	            	        top : pNameOffset.top + pName.outerHeight() + "px"
		         	    	            	    }).hide();
		         	                           
		         	                            //
		         	                            $.ajax({
		         	                            	url:Feng.ctxPath + '/collectBasicInformation/getcarry?carryNumber='+text1+'&contractNumber='+text,
		         	                            	type:"get",
		         	                            	dataType:'json',
		         	                            	success:function(data){
		         	                            		var modelCollection = data;
		         	                            		var carryBasic = modelCollection.carryBasicInformation;
		         	                            		var collectMoney = modelCollection.collectMoney;
		         	                            		var carryContractInformations = modelCollection.carryContractInformation;
		         	                            		/**
		         	                            		 * 初始化收款基本表
		         	                            		 */
		         	                            		//车号
		         	                            		$("#collectCarId").val(carryBasic.carryCarId);
		         	                            		//驾驶员
		         	                            		$("#collectCarDriver").val(carryBasic.carryCarDriver);
		         	                            		//联系电话
		         	                            		$("#collectCarDriverTell").val(carryBasic.carryCarDriverTell);
		         	                            		//手机
		         	                            		$("#collectCarDriverMobile").val(carryBasic.carryCarDriverMobile);
		         	                            		//车次
		         	                            		$("#collectCarNumber").val(carryBasic.carryNumber);
		         	                            		//物流线路
		         	                            		$("#collectRouteId").val(carryBasic.carryRouteId);
		         	                            		//始发站
		         	                            		$("#collectRouteStart").val(carryBasic.carryRouteStart);
		         	                            		//到站
		         	                            		$("#collectRouteEnd").val(carryBasic.carryRouteEnd);
		         	                            		//运费
		         	                            		$("#collectSumGoodsFreight").val();
		         	                            		//信息费
		         	                            		$("#collectSumGoodsMessagefee").val();
		         	                            		//提货费
		         	                            		$("#collectSumGoodsPickupCharge").val();
		         	                            		//总费用
		         	                            		$("#collectSumFee").val();
		         	                            		//中转站
		         	                            		$("#collectRouteTransferStation").val(carryBasic.carryRouteTransferStation);
		         	                            		//收款余额
		         	                            		$("#collectUncollectMoney").val(collectMoney.uncollectMoney);
		         	                            		$("#money").val(collectMoney.uncollectMoney);
		         	                            		/**
		         	                            		 * 初始化收款详情表
		         	                            		 */
		         	                            		for(i in carryContractInformations){
		         	                            			var tr =$("<tr class='logo'></tr>");
		         	                            			//装车号
		         	                            			var td1 = $("<td><input id='collectCarryId' name='collectCarryId' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td1.children().eq(0).val(carryBasic.carryId);
		         	                            			
		         	                            			//合同号
		         	                            			var td2 = $("<td><input id='collectContractNumber' name='collectContractNumber' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td2.children().eq(0).val(carryContractInformations[i].carryContractNumber);
		         	                            			
		         	                            			//发货人
		         	                            			var td3 = $("<td><input id='collectConsignerName' name='collectConsignerName' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td3.children().eq(0).val(carryContractInformations[i].carryConsignerName);
		         	                            			//发货人电话
		         	                            			var td4 = $("<td><input id='collectConsignerTell' name='collectConsignerTell' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td4.children().eq(0).val(carryContractInformations[i].carryConsignerTell);
		         	                            			//发货人地址
		         	                            			var td5 = $("<td><input id='collectConsignerPlace' name='collectConsignerPlace' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td5.children().eq(0).val(carryContractInformations[i].carryConsignerPlace);
		         	                            			
		         	                            			//收货人
		         	                            			var td6 = $("<td><input id='collectConsigneeName' name='collectConsigneeName' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td6.children().eq(0).val(carryContractInformations[i].carryConsigneeName);
		         	                            			//收货人电话
		         	                            			var td7 = $("<td><input id='collectConsigneeTell' name='collectConsigneeTell' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td7.children().eq(0).val(carryContractInformations[i].carryConsigneeTell);
		         	                            			//收货人地址
		         	                            			var td8 = $("<td><input id='collectConsigneePlace' name='collectConsigneePlace' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td8.children().eq(0).val(carryContractInformations[i].carryConsigneePlace);
		         	                            			
		         	                            			//货物编号
		         	                            			var td9 = $("<td><input id='collectGoodsId' name='collectGoodsId' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td9.children().eq(0).val(carryContractInformations[i].carryGoodsId);
		         	                            			//货物名称
		         	                            			var td10 = $("<td><input id='collectGoodsName' name='collectGoodsName' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td10.children().eq(0).val(carryContractInformations[i].carryGoodsName);
		         	                            			//货物规格
		         	                            			var td11 = $("<td><input id='collectGoodsModel' name='collectGoodsModel' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td11.children().eq(0).val(carryContractInformations[i].carryGoodsModel);
		         	                            			
		         	                            			//包装方式
		         	                            			var td12 = $("<td><input id='collectGoodsPackage' name='collectGoodsPackage' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td12.children().eq(0).val(carryContractInformations[i].carryGoodsPackage);
		         	                            			//发货数量(件)
		         	                            			var td13 = $("<td><input id='collectThisQuantity' name='collectThisQuantity' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td13.children().eq(0).val(carryContractInformations[i].carryThisQuantity);
		         	                            			//重量
		         	                            			var td14 = $("<td><input id='collectGoodsWeight' name='collectGoodsWeight' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td14.children().eq(0).val(carryContractInformations[i].carryGoodsWeight);
		         	                            			//体积
		         	                            			var td15 = $("<td><input id='collectGoodsVolume' name='collectGoodsVolume' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td15.children().eq(0).val(carryContractInformations[i].carryGoodsVolume);
		         	                            			
		         	                            			//运费
		         	                            			var td16 = $("<td><input id='collectGoodsFreight' name='collectGoodsFreight' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td16.children().eq(0).val(carryContractInformations[i].carryGoodsFreight);
		         	                            			//信息费
		         	                            			var td17 = $("<td><input id='collectGoodsMessagefee' name='collectGoodsMessagefee' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td17.children().eq(0).val(carryContractInformations[i].carryGoodsMessagefee);
		         	                            			//提货费
		         	                            			var td18 = $("<td><input id='collectGoodsPickupCharge' name='collectGoodsPickupCharge' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td18.children().eq(0).val(carryContractInformations[i].carryGoodsPickupCharge);
		         	                            			//仓库
		         	                            			var td19 = $("<td><input id='collectGoodsWarehouseName' name='collectGoodsWarehouseName' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td19.children().eq(0).val(carryContractInformations[i].carryGoodsWarehouseName);
		         	                            			//备注
		         	                            			var td20 = $("<td><input id='collectGoodsRemark' name='collectGoodsRemark' type='text' style='background-color:#eee' readonly='readonly'/></td>");
		         	                            			td20.children().eq(0).val(carryContractInformations[i].carryGoodsRemark);
		         	                            			
		         	                            			//删除最后一个统计的节点
		    		                                		$("#sumCopy").remove();
		    		                                		
		    		                                		tr.append(td1);
		    		                                		tr.append(td2);
		    		                                		tr.append(td3);
		    		                                		tr.append(td4);
		    		                                		tr.append(td5);
		    		                                		tr.append(td6);
		    		                                		tr.append(td7);
		    		                                		tr.append(td8);
		    		                                		tr.append(td9);
		    		                                		tr.append(td10);
		    		                                		tr.append(td11);
		    		                                		tr.append(td12);
		    		                                		tr.append(td13);
		    		                                		tr.append(td14);
		    		                                		tr.append(td15);
		    		                                		tr.append(td16);
		    		                                		tr.append(td17);
		    		                                		tr.append(td18);
		    		                                		tr.append(td19);
		    		                                		tr.append(td20);
		    		                                		$(".table1").append(tr);
		    		                                		 $(".table1").append("<tr id='sumCopy'><td colspan='12'>总计</td><td id='carryCount'></td><td id='sumWeight'></td><td id='sumVolume'></td><td id='sumFreight'></td><td id='sumMessagefee'></td><td id='sumPickupCharge'></td><td colspan='2'></td>");
		         	                            		}
		         	                            		initCount();
		         	                            	}
		         	                            });
		         	                            //
		         	                       });
		               	            	});
		                             }
		                        }
	                            });
	                       });
                     });
        	   }
     }
  });},10);
});

$("body").click(function(){
	$("#showContract").hide();
	$("#showCarry").hide();
});

//数据清空
function clearData(){
	$("#collectCarId").val("");
	$("#collectCarDriver").val("");
	$("#collectCarDriverTell").val("");
	$("#collectCarDriverMobile").val("");
	$("#collectCarNumber").val("");
	$("#collectRouteId").val("");
	$("#collectRouteStart").val("");
	$("#collectRouteEnd").val("");
	$("#collectSumGoodsFreight").val("");
	$("#collectSumGoodsMessagefee").val("");
	$("#collectSumGoodsPickupCharge").val("");
	$("#collectRouteTransferStation").val("");
	$("#collectSumFee").val("");
	$("#collectThisMoney").val("");
	$("#collectUncollectMoney").val("");
	$("#collectRemark").val("");
	
	$(".logo").remove();
	
}
